import React from 'react'
import { Table, Input, InputNumber, Form, Button, Popconfirm } from 'antd';
import { connect } from 'dva';
import { checkInit } from '@/utils/util';

import IForm from '../components/SearchForm'

interface IContextProps {
  state: any;
  dispatch: ({ type }: { type: string }) => void;
}

const EditableContext = React.createContext({} as IContextProps);

class EditableCell extends React.Component<any> {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }: any) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `请输入${title}!`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
            children
          )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({ build_floor_area, loading, menu }) => ({
  list: build_floor_area.list || {},
  cond: build_floor_area.cond || {},
  loading: loading.effects['build_floor_area/queryPage'],
  buttons: menu.buttons,
}))
class EditableTable extends React.Component<any, any> {
  state = {
    editingKey: '',
    current: 1,
    floorId: '',
    data: [],
    dataCnt: 0,
  };
  columns: Array<any>;

  constructor(props) {
    super(props);

    this.columns = [{
      title: '序号',
      dataIndex: 'ind',
      render: (text) => <>{text < 10 ? `0${text}` : text}</>
    }, {
      title: '区域名称',
      dataIndex: 'name',
      editable: true,
    }, {
      title: '所属消控室',
      dataIndex: 'fireRoomName',
    }, {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        const { editingKey } = this.state;
        const editable = this.isEditing(record);
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <a
                  onClick={this.save.bind(this, form, record.id)}
                  style={{ marginRight: 8 }}
                >
                  保存
                </a>
              )}
            </EditableContext.Consumer>
            <a onClick={this.cancel.bind(this, record.id)}>取消</a>
          </span>
        ) : (
            editingKey === '' ? (
              <>
                <a style={{ marginRight: 15 }} onClick={this.edit.bind(this, record.id)}>编辑</a>
                <Popconfirm
                  okText='确定'
                  cancelText='取消'
                  title={'是否删除'}
                  onConfirm={this.handleDeleteConfirm.bind(this, record.id, record.floorId)}
                >
                  <a>删除</a>
                </Popconfirm>
              </>
            ) : (<span style={{ color: "#ccc" }}>编辑</span>)
          );
      },
    }];
  }

  isEditing = record => record.id === this.state.editingKey;

  cancel = (v = "") => {
    this.setState({ editingKey: '' });
  };

  save = (form, key) => {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.props.list.data];
      const index = newData.findIndex(item => key === item.id);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        const { dispatch } = this.props;
        dispatch({
          type: 'build_floor_area/update', payload: {
            ...item,
            ...row
          }
        })
        this.setState({ data: newData, editingKey: '' });
      } else {
        newData.push(row);
        this.setState({ data: newData, editingKey: '' });
      }
    });
  }

  edit = (key) => {
    this.setState({ editingKey: key });
  }

  queryData(offset = 0) {
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'build_floor_area/queryPage',
      payload: {
        floorId: params.id,
        pageNum: offset,
      },
    })
  }

  initCurrent() {
    this.setState({
      current: 0
    })
  }

  componentDidMount() {
    const { dispatch, match } = this.props;
    const { params } = match;
    checkInit() ? dispatch({ type: 'build_floor_area/initCond', payload: { floorId: params.id } }) : this.queryData()

    this.setState({
      floorId: params.id,
    });
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `build_floor_area/updateCond`, payload: cond }).then(() => {
      this.initCurrent()
    })
  }

  handleDeleteConfirm = (id, floorId) => {
    const { dispatch } = this.props
    dispatch({ type: 'build_floor_area/remove', payload: { id, floorId } })
  }

  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const { buttons, dispatch, list } = this.props;
    const { data = [], dataCnt } = list;

    const btnList = {};
    if (Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }

    const ans = Array.isArray(data) && data.map((v, ind) => ({
      ...v,
      ind: ind + 1
    }))

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      current: this.state.current,
      onChange: (current) => {
        this.setState({ current })
        this.queryData(current)
        this.cancel()
      },
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <div>
        <IForm current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['新增']} floorId={this.state.floorId} />
        <EditableContext.Provider value={this.props.form}>
          <Table
            components={components}
            bordered
            columns={Array.isArray(data) && data[0] && data[0].count > 1 ? columns : [...columns.slice(0, 2), ...columns.slice(3)]}
            rowClassName={() => "editable-row"}
            pagination={pagination}
            dataSource={ans}
            rowKey="id"
            loading={this.props.loading}
          />
        </EditableContext.Provider>
        <Button
          icon="rollback"
          style={{ marginLeft: '40px', marginTop: '-50px', float: 'left' }}
          onClick={() => {
            dispatch({ type: 'build_floor_area/insert' });
            window.history.back()
          }}
        >返回</Button>
      </div>
    );
  }
}

const EditableFormTable = Form.create()(EditableTable);

export default EditableFormTable